package com.maolong.spring.core.io;

import cn.hutool.core.lang.Assert;
import com.maolong.spring.utils.ClassUtils;

import java.io.FileNotFoundException;
import java.io.InputStream;


public class ClassPathResource implements Resource{
    private final String path;
    private ClassLoader classLoader;

    public ClassPathResource(String path) {
        this(path, (ClassLoader) null);
    }

    public ClassPathResource(String path, ClassLoader classLoader) {
        Assert.notNull(path, "Path must not be null");
        this.path = path;
        this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader());
    }

    @Override
    public InputStream getInputStream() throws FileNotFoundException {
        InputStream s = classLoader.getResourceAsStream(path);
        if (s == null){
            throw new FileNotFoundException(
                    this.path + " cannot be opened because it does not exist");
        }
        return s;
    }

    @Override
    public String getFileName() {
        int lastSlashIndex = path.lastIndexOf("/");
        if (lastSlashIndex != -1 && lastSlashIndex < path.length() - 1) {
            return path.substring(lastSlashIndex + 1);
        } else {
            return path;
        }
    }
}
